package org.spitter.web.controller;

import java.util.Date;

import javax.validation.Valid;

import org.spitter.core.model.Spittle;
import org.spitter.core.service.SpitterService;
import org.spitter.core.service.SpittleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/spittles")
public class SpittleController {

	@Autowired
	private SpittleService spittleService;
	@Autowired
	private SpitterService spitterService;

	/*
	 * show the create spittle form
	 */
	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String initCreateSpittleForm(Model model) {
		model.addAttribute(new Spittle());
		return "spittles/new";
	}

	/*
	 * creates a spittle with the data from the form
	 * redirects to user's spittles page
	 */
	@RequestMapping(method=RequestMethod.POST, value="/new")
	public String createSpitterFromForm(@Valid Spittle spittle,
			BindingResult bindingResult) {

		if (bindingResult.hasErrors()) {
			return "spittles/new";
		}
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String username = auth.getName(); // get logged in username

		spittle.setWhen(new Date());
		spittle.setSpitter(spitterService.getByUsername(username));
		spittleService.save(spittle);
		return "redirect:/spitters/spittles?spitter="+username;
	}
	
	/*
	 * RESTful spittle services
	 */
}
